package com.itheima.tanhua.server.interceptor;

import com.itheima.commons.holder.TokenHolder;
import com.itheima.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {


        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            throw new Exception("token不能为空");
        }

        // 将token转为userId
        Claims claims = JwtUtils.getClaims(authorization);
        Integer userId = (Integer) claims.get("userId");
        String phone = (String) claims.get("phone");
        if (Objects.isNull(userId) || StringUtils.isEmpty(phone)) {
            throw new Exception("token失效");
        }

        // 需要将解析后的userId，丢给controller，或者service
        // 没有其他的方式，只能依靠ThreadLoacl
        Map<String, String> data = new HashMap<>(2);
        data.put("userId",userId.toString());
        data.put("phone", phone);
        TokenHolder.set(data);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        // 这个步骤 能保证ThreadLoacl内存不会一致增长，导致溢出
        TokenHolder.remove();
    }
}